package com.example.androidhive;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditProductActivity extends Activity {

	EditText txtName;
	EditText txtPrice;
	EditText txtDesc;
	EditText txtCreatedAt;
	Button btnSave;
	Button btnDelete;

	String pid;

	// Progress Dialog
	private ProgressDialog pDialog;

	// JSON parser class
	JSONParser jsonParser = new JSONParser();

	// single product url
	private static final String url_product_detials = "http://mm.webdream.hu/android_connect/get_product_details.php";

	// url to update product
	private static final String url_update_product = "http://mm.webdream.hu/android_connect/update_product.php";

	// url to delete product
	private static final String url_delete_product = "http://mm.webdream.hu/android_connect/delete_product.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCT = "product";
	private static final String TAG_PID = "pid";
	private static final String TAG_NAME = "name";
	private static final String TAG_PRICE = "price";
	private static final String TAG_DESCRIPTION = "description";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.edit_product);

		// save button
		this.btnSave = (Button) this.findViewById(R.id.btnSave);
		this.btnDelete = (Button) this.findViewById(R.id.btnDelete);

		// getting product details from intent
		Intent i = this.getIntent();

		// getting product id (pid) from intent
		this.pid = i.getStringExtra(EditProductActivity.TAG_PID);

		// Getting complete product details in background thread
		new GetProductDetails().execute();

		// save button click event
		this.btnSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// starting background task to update product
				new SaveProductDetails().execute();
			}
		});

		// Delete button click event
		this.btnDelete.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// deleting product in background thread
				new DeleteProduct().execute();
			}
		});

	}

	/**
	 * Background Async Task to Get complete product details
	 * */
	class GetProductDetails extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			EditProductActivity.this.pDialog = new ProgressDialog(
					EditProductActivity.this);
			EditProductActivity.this.pDialog
					.setMessage("Loading product details. Please wait...");
			EditProductActivity.this.pDialog.setIndeterminate(false);
			EditProductActivity.this.pDialog.setCancelable(true);
			EditProductActivity.this.pDialog.show();
		}

		/**
		 * Getting product details in background thread
		 * */
		@Override
		protected String doInBackground(String... params) {

			// updating UI from Background Thread

			// Check for success tag
			int success;
			try {
				// Building Parameters
				List<NameValuePair> params1 = new ArrayList<NameValuePair>();
				params1.add(new BasicNameValuePair("pid",
						EditProductActivity.this.pid));

				// getting product details by making HTTP request
				// Note that product details url will use GET request
				JSONObject json = EditProductActivity.this.jsonParser
						.makeHttpRequest(
								EditProductActivity.url_product_detials, "GET",
								params1);

				// check your log for json response
				Log.d("Single Product Details", json.toString());

				// json success tag
				success = json.getInt(EditProductActivity.TAG_SUCCESS);
				if (success == 1) {
					// successfully received product details
					JSONArray productObj = json
							.getJSONArray(EditProductActivity.TAG_PRODUCT); // JSON
																			// Array

					// get first product object from JSON Array
					final JSONObject product = productObj.getJSONObject(0);

					// product with this pid found
					// Edit Text
					EditProductActivity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							EditProductActivity.this.txtName = (EditText) EditProductActivity.this
									.findViewById(R.id.inputName);
							EditProductActivity.this.txtPrice = (EditText) EditProductActivity.this
									.findViewById(R.id.inputPrice);
							EditProductActivity.this.txtDesc = (EditText) EditProductActivity.this
									.findViewById(R.id.inputDesc);

							// display product data in EditText
							try {
								EditProductActivity.this.txtName.setText(product
										.getString(EditProductActivity.TAG_NAME));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							try {
								EditProductActivity.this.txtPrice.setText(product
										.getString(EditProductActivity.TAG_PRICE));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							try {
								EditProductActivity.this.txtDesc.setText(product
										.getString(EditProductActivity.TAG_DESCRIPTION));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
				} else {
					// product with pid not found
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once got all details
			EditProductActivity.this.pDialog.dismiss();
		}
	}

	/**
	 * Background Async Task to Save product Details
	 * */
	class SaveProductDetails extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			EditProductActivity.this.pDialog = new ProgressDialog(
					EditProductActivity.this);
			EditProductActivity.this.pDialog.setMessage("Saving product ...");
			EditProductActivity.this.pDialog.setIndeterminate(false);
			EditProductActivity.this.pDialog.setCancelable(true);
			EditProductActivity.this.pDialog.show();
		}

		/**
		 * Saving product
		 * */
		@Override
		protected String doInBackground(String... args) {

			// getting updated data from EditTexts
			String name = EditProductActivity.this.txtName.getText().toString();
			String price = EditProductActivity.this.txtPrice.getText()
					.toString();
			String description = EditProductActivity.this.txtDesc.getText()
					.toString();

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(EditProductActivity.TAG_PID,
					EditProductActivity.this.pid));
			params.add(new BasicNameValuePair(EditProductActivity.TAG_NAME,
					name));
			params.add(new BasicNameValuePair(EditProductActivity.TAG_PRICE,
					price));
			params.add(new BasicNameValuePair(
					EditProductActivity.TAG_DESCRIPTION, description));

			// sending modified data through http request
			// Notice that update product url accepts POST method
			JSONObject json = EditProductActivity.this.jsonParser
					.makeHttpRequest(EditProductActivity.url_update_product,
							"POST", params);

			// check json success tag
			try {
				int success = json.getInt(EditProductActivity.TAG_SUCCESS);

				if (success == 1) {
					// successfully updated
					Intent i = EditProductActivity.this.getIntent();
					// send result code 100 to notify about product update
					EditProductActivity.this.setResult(100, i);
					EditProductActivity.this.finish();
				} else {
					// failed to update product
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once product uupdated
			EditProductActivity.this.pDialog.dismiss();
		}
	}

	/*****************************************************************
	 * Background Async Task to Delete Product
	 * */
	class DeleteProduct extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			EditProductActivity.this.pDialog = new ProgressDialog(
					EditProductActivity.this);
			EditProductActivity.this.pDialog.setMessage("Deleting Product...");
			EditProductActivity.this.pDialog.setIndeterminate(false);
			EditProductActivity.this.pDialog.setCancelable(true);
			EditProductActivity.this.pDialog.show();
		}

		/**
		 * Deleting product
		 * */
		@Override
		protected String doInBackground(String... args) {

			// Check for success tag
			int success;
			try {
				// Building Parameters
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("pid",
						EditProductActivity.this.pid));

				// getting product details by making HTTP request
				JSONObject json = EditProductActivity.this.jsonParser
						.makeHttpRequest(
								EditProductActivity.url_delete_product, "POST",
								params);

				// check your log for json response
				Log.d("Delete Product", json.toString());

				// json success tag
				success = json.getInt(EditProductActivity.TAG_SUCCESS);
				if (success == 1) {
					// product successfully deleted
					// notify previous activity by sending code 100
					Intent i = EditProductActivity.this.getIntent();
					// send result code 100 to notify about product deletion
					EditProductActivity.this.setResult(100, i);
					EditProductActivity.this.finish();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once product deleted
			EditProductActivity.this.pDialog.dismiss();

		}

	}
}
